<template>
	<div>
		<BreadCrumb pathOne="咨询公告管理"></BreadCrumb>
		<el-form :inline="true">
			<el-form-item label="咨询公告名" size="large">
				<el-input size="large" clearable v-model="noticeName" placeholder="请输入咨询公告名"></el-input>
			</el-form-item>
			<el-form-item label="公告内容" size="large">
				<el-input size="large" clearable v-model="content" placeholder="请输入公告内容"></el-input>
			</el-form-item>
			<el-form-item size="large">
				<el-button type="primary" @click="query">搜索</el-button>
				<el-button type="primary" @click="createOrUpdate('')">新增咨询公告</el-button>
				<el-button type="danger" @click="batchDelete">批量删除</el-button>
			</el-form-item>
		</el-form>
		<el-table style="width: 100%;" border :data="tableData" :row-style="{ height: '50px' }"
			:header-cell-style="{textAlign: 'center'}" :cell-style="{ textAlign: 'center' }"
			@selection-change="handleSelectionChange">
			<el-table-column type="selection" width="60" />
			<el-table-column fixed prop="id" label="ID" width="200" />
			<el-table-column prop="noticeName" label="公告名" width="200" show-overflow-tooltip />
			<el-table-column prop="content" label="公告内容" width="280" show-overflow-tooltip />
			<el-table-column prop="noticeTime" label="发布时间" />
			<el-table-column label="缩略图" width="120">
				<template #default="scope">
					<el-avatar shape="square" size="large" :src="scope.row.url" />
				</template>
			</el-table-column>
			<el-table-column fixed="right" label="操作">
				<template #default="scope">
					<el-button size="small" type="primary" @click="createOrUpdate(scope.row.id)">编辑</el-button>
					<el-button size="small" type="danger" @click="remove(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="800" style="margin-bottom: 60px;"
			@close="handleClose">
			<el-form>
				<el-form-item label="公告名" label-width="auto" label-position='top'>
					<el-input size="large" v-model="form.noticeName" autocomplete="off" placeholder="请输入公告名" />
				</el-form-item>
				<el-form-item label="公告内容" label-width="auto" label-position='top'>
					<el-input size="large" v-model="form.content" autocomplete="off" placeholder="请输入公告内容" />
				</el-form-item>
				<el-form-item label="缩略图" label-position="top">
					<el-upload class="avatar-uploader" :action="baseURL+ 'upload'" :show-file-list="false"
						:on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" name="file">
						<img v-if="imageUrl" :src="imageUrl" class="avatar" />
						<el-icon v-else class="avatar-uploader-icon">
							<Plus />
						</el-icon>
					</el-upload>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogFormVisible = false">取消</el-button>
					<el-button type="primary" @click="dialogFormVisible = false,add()">
						确定
					</el-button>
				</div>
			</template>
		</el-dialog>
		<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10,15, 20]"
			:size="size" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
			@current-change="handleCurrentChange" />
	</div>
</template>

<script lang="ts" setup>
	import BreadCrumb from "../components/BreadCrumb.vue"
	import { useRouter } from 'vue-router'
	import { useCounterStore } from '../stores/counter'
	import {
		getCurrentInstance,
		onMounted,
		ref
	} from 'vue'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import {
		Plus
	} from '@element-plus/icons-vue'
	import http from '@/util/http';
	const baseURL = http.defaults.baseURL
	const axios = getCurrentInstance().appContext.config.globalProperties.axios;
	const tableData = ref([])
	const total = ref(0)
	const formatTimestamp = (timestamp : string) => {
		if (!timestamp) return ''
		const date = new Date(timestamp)
		const year = date.getFullYear()
		const month = date.getMonth() + 1
		const day = date.getDate()
		const hours = date.getHours().toString().padStart(2, '0')
		const minutes = date.getMinutes().toString().padStart(2, '0')
		const seconds = date.getSeconds().toString().padStart(2, '0')
		return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`
	}
	const currentPage = ref(1)
	const pageSize = ref(10)
	const size = 'default'
	const noticeName = ref('')
	const content = ref('')
	const handleSizeChange = (val) => {
		pageSize.value = val;
		query();
	}
	const handleCurrentChange = (val) => {
		currentPage.value = val
		query();
	}
	const query = () => {
		axios.get(`/consultNotice/findNoticePage`, {
			params: {
				noticeName: noticeName.value,
				content: content.value,
				pageNum: currentPage.value,
				pageSize: pageSize.value
			}
		}).then(resp => {
			tableData.value = resp.data.list
			total.value = resp.data.total
			tableData.value.forEach(item => {
				item.url = item.url
			})
		})
	}
	const dialogFormVisible = ref(false)
	const handleClose = () => {
		form.value.noticeName = ''
		form.value.content = ''
		form.value.url = ''
		form.value.id = ''
		imageUrl.value = ''
	}
	const form = ref({
		noticeName: "",
		id: "",
		content: "",
		url: "",
		userId: 0
	})
	const dialogTitle = ref()
	const createOrUpdate = (id) => {
		dialogFormVisible.value = true
		if (id === '') {
			dialogTitle.value = "新增咨询公告"
			form.value.noticeName = ''
			form.value.content = ''
			form.value.url = ''
			form.value.id = ''
			form.value.userId = counter.userInfo.id
			imageUrl.value = ''
		} else {
			dialogTitle.value = "编辑咨询公告"
			axios.get(`/consultNotice/findById/${id}`).then(resp => {
				form.value = resp.data
				imageUrl.value = resp.data.url
			})
		}
	}
	const add = () => {
		if (form.value.id == '') {
			axios.post('/consultNotice/add', form.value).then(resp => {
				if (resp.data.code == 200) {
					ElMessage({
						message: '新增成功',
						type: 'success',
					})
				} else {
					ElMessage.error('新增失败')
				}
			}).finally(() => {
				query();
			})
		} else {
			axios.put('/consultNotice/edit', form.value).then(resp => {
				if (resp.data.code == 200) {
					ElMessage({
						message: '修改成功',
						type: 'success',
					})
				} else {
					ElMessage.error('修改失败')
				}
			}).finally(() => {
				query();
			})
		}
	}
	const remove = (id) => {
		ElMessageBox.confirm(
			'此操作将永久删除该数据, 是否继续?',
			'提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
		}
		)
			.then(() => {
				axios.delete(`/consultNotice/remove/${id}`).then((resp) => {
					if (resp.data.code == 200) {
						ElMessage({
							message: '删除成功',
							type: 'success',
						})
					} else {
						ElMessage.error('删除失败')
					}
				}).finally(() => {
					query();
				});
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				})
			})
	}
	const ids = ref('')
	const handleSelectionChange = (selection) => {
		ids.value = selection.map(item => item.id)
	}
	const batchDelete = () => {
		if (!ids.value || ids.value.length === 0) {
			ElMessage.info('请选择要删除的数据')
			return
		}
		ElMessageBox.confirm('此操作将永久删除该数据, 是否继续?', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
			axios.delete('/consultNotice/removeBatch', { data: ids.value }).then(res => {
				ElMessage.success('删除成功')
				query();
			})
		}).catch(() => {
			ElMessage.info('已取消删除')
		}).finally(() => {
			query();
		});
	}
	const imageUrl = ref('')
	// 上传图片处理
	const handleAvatarSuccess = (response) => {
		// 后端返回的是相对路径，比如 "/upload/20250717/xxxx.jpg"
		form.value.url = response.data; // 只存储相对路径
		imageUrl.value = response.data; // 展示时拼接完整路径
	}

	const beforeAvatarUpload = (file) => {
		const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
		const isLt2M = file.size / 1024 / 1024 < 2;

		if (!isJPG) {
			ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');
		}
		if (!isLt2M) {
			ElMessage.error('上传头像图片大小不能超过 2MB!');
		}
		return isJPG && isLt2M;
	}
	const counter = useCounterStore()
	const router = useRouter()

	onMounted(() => {
		query()
	})
</script>

<style scoped>
	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}
</style>